from django.utils.deprecation import MiddlewareMixin
from django.utils.timezone import now
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.models import AnonymousUser
import logging

logger = logging.getLogger(__name__)


class CustomUser:
    """ 自定义用户类，模拟 Django 的 User """
    def __init__(self, username):
        self.username = username
        self.is_authenticated = True  # 让 Django 认为用户已登录
        # print('CustomUser- is_authenticated')

class IdleSessionTimeoutMiddleware(MiddlewareMixin):
    def process_request(self, request):
        open_urls = [
                    settings.LOGIN_URL,
                    '/static/',
                    '/favicon.ico',
                ]
        # print(1)
        """ 设置 request.user，使其支持 is_authenticated """
        username = request.session.get('username')
        if username:
            # print(2)
            request.user = CustomUser(username)  # 设置自定义用户
        else:
            # print(3)
            request.user = AnonymousUser()  # 未登录则设为空用户

        if not request.user.is_authenticated and not any(request.path.startswith(url) for url in open_urls):
            # print(4)
            return redirect(f"{settings.LOGIN_URL}")

        # 处理空闲超时
        last_activity = request.session.get('last_activity')
        if last_activity:
            # print(5)
            timeout_period = getattr(settings, 'SESSION_IDLE_TIMEOUT', 300)
            if (now() - now().fromisoformat(last_activity)).total_seconds() > timeout_period:
                request.session.flush()
                return redirect(f"{settings.LOGIN_URL}?timeout=1")

        # 更新最后活动时间
        # print(6)
        request.session['last_activity'] = now().isoformat()

# class LoginRequiredMiddleware(MiddlewareMixin):
#     def process_request(self, request):
#         print(7)
#         """ 处理用户身份认证 """
#
#         open_urls = [
#             settings.LOGIN_URL,
#             '/static/',
#             '/favicon.ico',
#         ]
#
#         # **手动设置 request.user**
#         username = request.session.get('username')
#         if username:
#             print(8)
#             request.user = CustomUser(username)  # 绑定用户
#         else:
#             print(9)
#             request.user = AnonymousUser()  # 未登录用户
#
#         # **检查是否需要登录**
#         if not request.user.is_authenticated and not any(request.path.startswith(url) for url in open_urls):
#             print("未登录，重定向至登录页")
#             return redirect(f"{settings.LOGIN_URL}")
